package com.jboost.modules.app.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Maps;
import com.jboost.common.api.vo.Result;
import com.jboost.modules.app.constant.BaseResult;
import com.jboost.modules.app.dto.HsOrderCountDto;
import com.jboost.modules.app.dto.Wlck;
import com.jboost.modules.app.dto.resp.HsOrderCountResp;
import com.jboost.modules.app.service.ChatGptService;
import com.jboost.modules.app.util.StrategyFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Api(tags = "客户管理")
@RestController
@RequestMapping("/plugin")
@Slf4j
@AllArgsConstructor
public class PluginController {


    ChatGptService chatGptService;


    @GetMapping(value = "/transferDh")
    @ApiOperation(value = "数据转换", notes = "数据转换")
    public Result<List<String>> pushDh(@RequestParam(name = "msg") String msg) throws Exception {
        return Result.OK(Arrays.asList(msg.split(",")));
    }

    @GetMapping(value = "/transfer")
    @ApiOperation(value = "数据转换", notes = "数据转换")
    public Result<String> push(@RequestParam(name = "msg") String msg) throws Exception {

        String replace = msg.replace(",", "-");
        return Result.OK(replace);
    }

    @GetMapping(value = "/merge")
    @ApiOperation(value = "数据转换", notes = "数据转换")
    public Collection<Wlck> merge(@RequestParam(name = "msg") String msg,@RequestParam(name = "xh") String xh) throws Exception {
        List<Wlck> wlcks = new ArrayList<Wlck>();
        String[] split = msg.split(",");
        for (String s : split) {
            String[] split1 = s.split("\\|");
            Wlck wlck = new Wlck(split1[0], split1[1], split1[2]);
            if (Objects.equals(wlck.getA(),xh)) {
                wlcks.add(wlck);
            }
        }
        Map<String, Wlck> wlckMap = wlcks.stream().collect(Collectors.toMap(e -> String.valueOf(e.getA()) + String.valueOf(e.getB()), Function.identity(), (a, b) -> {
            b.setC(Integer.parseInt(a.getC()) + Integer.parseInt(b.getC()) + "");
            return b;
        }));
        return wlckMap.values();
    }

    @GetMapping(value = "/cj5")
    @ApiOperation(value = "cj5", notes = "cj5")
    public List<Map> cj5(@RequestParam(name = "wl_list",required = false,defaultValue = "") String wl_list,@RequestParam(name = "ilmc_list",required = false,defaultValue = "") String ilmc_list,
                              @RequestParam(name = "gg_list",required = false,defaultValue = "") String gg_list,@RequestParam(name = "kz_list",required = false,defaultValue = "") String kz_list,
                              @RequestParam(name = "bdb_list",required = false,defaultValue = "") String bdb_list,
                              @RequestParam(name = "sf_list",required = false,defaultValue = "") String sf_list,@RequestParam(name = "bw_list",required = false,defaultValue = "") String bw_list,@RequestParam(name = "wild_list",required = false,defaultValue = "") String wild_list
            ,@RequestParam(name = "dw_list",required = false,defaultValue = "") String dw_list,@RequestParam(name = "wljd_list",required = false,defaultValue = "") String wljd_list,@RequestParam(name = "ywlbm_list",required = false,defaultValue = "") String ywlbm_list,@RequestParam(name = "gyswlbm_list",required = false,defaultValue = "") String gyswlbm_list
            ,@RequestParam(name = "sqps_list",required = false,defaultValue = "") String sqps_list
            ,@RequestParam(name = "sfbhyh_list",required = false,defaultValue = "") String sfbhyh_list
            ,@RequestParam(name = "yszwmc_list",required = false,defaultValue = "") String yszwmc_list
            ,@RequestParam(name = "ysywmc_list",required = false,defaultValue = "") String ysywmc_list
            ,@RequestParam(name = "sh_list",required = false,defaultValue = "") String sh_list
            ,@RequestParam(name = "ysdm_list",required = false,defaultValue = "") String ysdm_list
            ,@RequestParam(name = "tsyq_list",required = false,defaultValue = "") String tsyq_list) throws Exception {
        List<Map> list = Lists.newArrayList();
        String[] sqps = sqps_list.split(",");
        String[] sfbhyh = sfbhyh_list.split(",");
        String[] yszwmc = yszwmc_list.split(",");
        String[] ysywmc = ysywmc_list.split(",");
        String[] sh = sh_list.split(",");
        String[] ysdm = ysdm_list.split(",");
        String[] tsyq = tsyq_list.split(",");
        String[] gyswlbm = gyswlbm_list.split(",");

        String[] wilds = wild_list.split(",");
        String[] wls = wl_list.split(",");
        String[] ilmcs = ilmc_list.split(",");
        String[] ggs = gg_list.split(",");
        String[] kzs = kz_list.split(",");
        String[] bdbs = bdb_list.split(",");
        String[] sfs = sf_list.split(",");
        String[] bws = bw_list.split(",");
        String[] dws = dw_list.split(",");
        String[] wljd = wljd_list.split(",");
        String[] ywlbm = ywlbm_list.split(",");
        for (int i=0;i<wilds.length;i++){
            Map map = new HashMap();
            try {
                map.put("tsyq", tsyq[i]);
            }catch (Exception exception){

            }
            try {
                map.put("gyswlbm", gyswlbm[i]);
            }catch (Exception exception){

            }
            try {
                map.put("ysywmc", ysywmc[i]);
            }catch (Exception exception){

            }
            try {
                map.put("ysdm", ysdm[i]);
            }catch (Exception exception){

            }
            try {
                map.put("sh", sh[i]);
            }catch (Exception exception){

            }
            try {
                map.put("sqps", sqps[i]);
            }catch (Exception exception){

            }
            try {
                map.put("yszwmc", yszwmc[i]);
            }catch (Exception exception){

            }
            try {
                map.put("sfbhyh", sfbhyh[i]);
            }catch (Exception exception){

            }
            try {
                map.put("wldl", wilds[i]);
            }catch (Exception exception){

            }
            try {
                map.put("ywlbm", ywlbm[i]);
            }catch (Exception exception){

            }
            try {
                map.put("wljd", wljd[i]);
            }catch (Exception exception){

            }
            try{
            map.put("wl",wls[i]);
        }catch (Exception exception){

        }
        try{
            map.put("ilmc",ilmcs[i]);
    }catch (Exception exception){

    }
    try{
            map.put("gg",ggs[i]);
}catch (Exception exception){

        }
        try{
            map.put("kz",kzs[i]);
        }catch (Exception exception){

        }
        try{
            map.put("bdb",bdbs[i]);
        }catch (Exception exception){

        }
        try{
            map.put("sf",sfs[i]);
        }catch (Exception exception){

        }
        try{
            map.put("bw",bws[i]);
        }catch (Exception exception){

        }
            try{
                map.put("dw",dws[i]);
            }catch (Exception exception){

            }
            list.add(map);
        }
        return list;
    }


    @GetMapping(value = "/cj8")
    @ApiOperation(value = "cj7", notes = "cj7")
    public Map<String,List<String[]>> cj7(@RequestParam(name = "msg") String msg) throws Exception {
        HashMap<String, List<String[]>> map = Maps.newHashMap();
        String[] split = msg.split(",");
        List<String[]> mianliao = Arrays.stream(split).filter(e -> Objects.equals(e.split("\\|")[0], "面料")).map(e1->e1.split("\\|")).collect(Collectors.toList());
        List<String[]> fliao = Arrays.stream(split).filter(e -> Objects.equals(e.split("\\|")[0], "辅料")).map(e1->e1.split("\\|")).collect(Collectors.toList());
        map.put("mianliao",mianliao);
        map.put("fliao",fliao);
        return map;
    }


    @GetMapping(value = "/dollars")
    @ApiOperation(value = "cj7", notes = "cj7")
    public Result<String> dollars(@RequestParam(name = "msg") String msg,@RequestParam(name = "type") String type) throws Exception {
        double v = Double.parseDouble(msg);
//        if (Objects.equals(type,"美分")) {
//            v = v * 100;
//        }
        return Result.OK(convert(v));
    }


    public static String convert(double amount) {
        // 分离整数和小数部分
        long dollars = (long) amount;
        long cents = Math.round((amount - dollars) * 100);

        String dollarWords = numberToWords(dollars);

        // 构建最终结果
        String result = dollarWords + " DOLLARS";
        if (cents > 0) {
            String centWords = numberToWords(cents);
            result += " AND " + centWords + " CENTS";
        }
        result += " ONLY";

        return result;
    }
    private static final String[] units = {
            "", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN",
            "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTEEN", "NINETEEN"
    };
    private static final String[] tens = {
            "", "", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY"
    };

    private static String convertLessThanOneThousand(int number) {
        if (number == 0) return "";
        if (number < 20) return units[number];
        if (number < 100) return tens[number / 10] + ((number % 10 != 0) ? " " : "") + units[number % 10];
        return units[number / 100] + " HUNDRED" + ((number % 100 != 0) ? " AND " : "") + convertLessThanOneThousand(number % 100);
    }
    public static String numberToWords(long number) {
        if (number == 0) return "ZERO";

        String[] scaleNames = {"", "THOUSAND", "MILLION", "BILLION", "TRILLION"};
        String words = "";

        for (int i = 0; number > 0; i++) {
            long chunk = number % 1000;
            if (chunk != 0) {
                String chunkWords = convertLessThanOneThousand((int)chunk);
                if (i > 0) chunkWords += " " + scaleNames[i];
                words = chunkWords + (words.isEmpty() ? "" : " ") + words;
            }
            number /= 1000;
        }

        return words;
    }


    @PostMapping(value = "/hs-order")
    @ApiOperation(value = "数据转换", notes = "数据转换")
    public Result<List<HsOrderCountResp>> hsOrder(@RequestBody String msg) throws Exception {

        String[] split = msg.split(",");
        List<HsOrderCountDto> hsOrderCountDtos = new ArrayList<>();
        for (String s : split) {
            HsOrderCountDto hsOrderCountDto = getByCLass(s);
            String field4 = hsOrderCountDto.getField4();
            List<HsOrderCountDto> filed4List = trasnfer(field4, hsOrderCountDto);
            hsOrderCountDtos.addAll(filed4List);
        }
        List<HsOrderCountResp> hsOrderCountResps = new ArrayList<>();

        //订单数据统计
        Map<String, List<HsOrderCountDto>> collect = hsOrderCountDtos.stream().collect(
                Collectors.groupingBy(i -> i.getField1() + "|" + i.getField2() + "|" + i.getField3() + "|" + i.getField4(), Collectors.toList()));
        collect.entrySet().forEach(e1 -> {
            String key = e1.getKey();
            String[] split1 = key.split("\\|");
            HsOrderCountResp hsOrderCountResp = new HsOrderCountResp();
            hsOrderCountResp.setField1(split1[0]);
            hsOrderCountResp.setField2(split1[1]);
            hsOrderCountResp.setField3(split1[2]);
            hsOrderCountResp.setField4(split1[3]);
            hsOrderCountResp.setField5(String.valueOf(e1.getValue().stream().mapToInt(e -> {
                return Integer.parseInt(e.getField6());
            }).sum()));
            hsOrderCountResps.add(hsOrderCountResp);
        });
        //订单分类统计
        Map<String, List<HsOrderCountDto>> collect1 = hsOrderCountDtos.stream().collect(
                Collectors.groupingBy(i -> i.getField7() + "|" + i.getField8(), Collectors.toList()));
        collect1.entrySet().forEach(e1 -> {
            String key = e1.getKey();
            String[] split1 = key.split("\\|");
            HsOrderCountResp hsOrderCountResp = new HsOrderCountResp();
            hsOrderCountResp.setField1(split1[0]);
            hsOrderCountResp.setField2("/");
            hsOrderCountResp.setField3("/");
            hsOrderCountResp.setField4(split1[1]);
            hsOrderCountResp.setField5(String.valueOf(e1.getValue().stream().mapToInt(e -> {
                return Integer.parseInt(e.getField6());
            }).sum()));
            hsOrderCountResps.add(hsOrderCountResp);
        });
        return Result.OK(hsOrderCountResps);
    }

    private List<HsOrderCountDto> trasnfer(String field4, HsOrderCountDto hsOrderCountDto) {
        List<HsOrderCountDto> list = Lists.newArrayList();
        String[] split = field4.split("\\-");
        for (String s : split) {
            String[] split1 = s.split("\\*");
            if (!Objects.equals(split1[0],"0")) {
                HsOrderCountDto hsOrderCountDto1 = new HsOrderCountDto();
                BeanUtil.copyProperties(hsOrderCountDto, hsOrderCountDto1);
                hsOrderCountDto1.setField4(split1[0]);
                hsOrderCountDto1.setField6(Integer.parseInt(split1[1]) * Integer.parseInt(hsOrderCountDto1.getField5()) + "");
                list.add(hsOrderCountDto1);
            }else {
                HsOrderCountDto hsOrderCountDto1 = new HsOrderCountDto();
                BeanUtil.copyProperties(hsOrderCountDto, hsOrderCountDto1);
                hsOrderCountDto1.setField6("0");
                list.add(hsOrderCountDto1);
            }
        }
        return list;
    }

    private HsOrderCountDto getByCLass(String s) throws IllegalAccessException {
        HsOrderCountDto hsOrderCountDto = new HsOrderCountDto();
        Field[] declaredFields = hsOrderCountDto.getClass().getDeclaredFields();
        String[] split = s.split("\\|");
        for (int i = 0; i < declaredFields.length; i++) {
            declaredFields[i].set(hsOrderCountDto, split[i]);
        }
        return hsOrderCountDto;
    }


}
